package com.weixing.mall.provider.auth.member.openid;

import com.weixing.mall.provider.enums.LoginEnum;
import com.weixing.mall.provider.support.wechat.WechatUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.weixin4j.Weixin;
import org.weixin4j.component.SnsComponent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MemberOpenIdAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    private String codeParameter = "code";
    private boolean postOnly = true;

    public MemberOpenIdAuthenticationFilter() {
        super(new AntPathRequestMatcher(LoginEnum.MEMBER_OPENID.getValue(), "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String code = this.obtainCode(request);
            Assert.hasText(code, "未授权微信登录");
            code = code.trim();
            String openId = WechatUtil.getOpenIdByCode(code);
            MemberOpenIdAuthenticationToken authRequest = new MemberOpenIdAuthenticationToken(openId);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter(this.codeParameter);
    }

    protected void setDetails(HttpServletRequest request, MemberOpenIdAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public void setCodeParameter(String code) {
        Assert.hasText(code, "code parameter must not be empty or null");
        this.codeParameter = code;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getCodeParameter() {
        return this.codeParameter;
    }

}